package setupdb;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import db.DBRecord;


public class ArtistDB {

	private Map<String, List<DBRecord>> records;
	private List<String> lowCaseArtists;
	private BufferedWriter writer;

	public ArtistDB(String name) {
		records = new HashMap<String, List<DBRecord>>();
		lowCaseArtists = new ArrayList<String>();
		try {
			writer = new BufferedWriter(new FileWriter(new File(
					Main.DB_OUT_FOLDER, name)));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addRecord(DBRecord record) {
		String artist = record.getArtist().toLowerCase();

		if (!records.containsKey(artist)) {
			lowCaseArtists.add(artist);
			records.put(artist, new ArrayList<DBRecord>());
		}
		records.get(artist).add(record);
	}

	public void writeSortedRecords() {
		sortArtists();

		for (int i = 0; i < lowCaseArtists.size(); i++) {
			List<DBRecord> artistRecords = records.get(lowCaseArtists.get(i));
			writeDB(artistRecords);
		}
		try {
			writer.close();
		} catch (IOException e) {
			System.err.println("Cannot close artist DB writer.");
			e.printStackTrace();
		}
	}

	private void writeDB(List<DBRecord> artistRecords) {
		try {
			// TODO Sort
			writer.append(artistRecords.get(0).getArtist() + "\r\n");
			
			for (int i = 0; i < artistRecords.size(); i++) {
				DBRecord record = artistRecords.get(i);
				writer.append("\t" + record.getTitle() + "\r\n");
				writer.append("\t\t" + record.getRelativeFolder() + "\r\n");
				writer.append("\t\t" + record.getRating() + "\r\n");
			}
		} catch (IOException e) {
			System.err.println("Cannot write to DB : " + ".");
		}
	}

	private void sortArtists() {
		String[] _artists = lowCaseArtists.toArray(new String[lowCaseArtists
				.size()]);
		Arrays.sort(_artists);
		lowCaseArtists = Arrays.asList(_artists);
	}

}
